package com.pi.smart.base.task.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.pi.base.enumerate.redis.RedisCacheEnum;
import com.pi.base.util.cache.RedisUtil;
import com.pi.dc.dao.entity.DcBedNatureEntity;
import com.pi.dc.service.DcBedService;
import com.pi.smart.base.task.UserSleepLogTask;
import com.pi.smart.client.ins.bed.annotation.ForBedIns;
import com.pi.smart.client.ins.bed.category.BedInsEnum;
import com.pi.smart.client.ins.bed.domain.SmartBedCmd;
import com.pi.smart.client.ins.bed.variety.BedInsHandler;

@ForBedIns(ins = BedInsEnum.WIFI_CONFIRM)
@Component
public class SmartBedWifiSetResponseProcessor implements BedInsHandler{
  
  private static final Logger logger = LoggerFactory.getLogger(UserSleepLogTask.class);
  
  @Autowired
  private DcBedService bedService;
  
  @Override
  public void process(SmartBedCmd cmd) {
    if(null == cmd)
      return;
    try{
      handle(cmd);
    }catch(Exception e){
      logger.error("[wifi_logger] 处理WIFI设置确认记录失败", e);
    }
  }

  private void handle(SmartBedCmd cmd){
    logger.info("[wifi_logger]获取到WIFI设置确认记录：{}", JSON.toJSONString(cmd));
    if(0 == (cmd.getCmd()[13] & 0xFF)){
      logger.info("[wifi_logger] wifi设置下发成功：{}", cmd.getDevCode());
      RedisUtil.del(RedisCacheEnum.SMART_DEVICE_WIFI, new Object[]{cmd.getDevCode()});
      DcBedNatureEntity entity = bedService.getOrCreateBedNature(cmd.getDevCode());
      entity.setWifiStatus(2);
      bedService.activeBedWifi(cmd.getDevCode(), 2);
    }
  }
}
